package com.spic.business.train.trainCertificate.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.plan.comunication.domain.PlanCommunicationSupport;
import com.spic.business.train.trainCertificate.domain.TrainCertificate;
import com.spic.business.train.trainCertificate.mapper.TrainCertificateMapper;
import com.spic.business.train.trainCertificate.service.ITrainCertificateService;
import com.spic.business.vehicle.carInfo.constant.CarConstant;
import com.spic.common.core.domain.R;
import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysDept;
import com.spic.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 人员证书Service业务层处理
 *
 * @author spic
 * @date 2021-11-25
 */
@Service
public class TrainCertificateServiceImpl implements ITrainCertificateService
{
    private static final Logger log = LoggerFactory.getLogger(PlanCommunicationSupport.class);
    private static final String trainingSystemUrl = "https://sd.sdmkpx.com:10007/quanyuanApi/blade-quanyuan-exam/external/certificatesapi/unAuth/getCertificatesList";
    @Autowired
    private TrainCertificateMapper trainCertificateMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询人员证书
     *
     * @param trainCertificateId 人员证书主键
     * @return 人员证书
     */
    @Override
    public TrainCertificate selectTrainCertificateByTrainCertificateId(String trainCertificateId)
    {
        return trainCertificateMapper.selectTrainCertificateByTrainCertificateId(trainCertificateId);
    }

    /**
     * 查询人员证书列表
     *
     * @param trainCertificate 人员证书
     * @return 人员证书
     */
    @Override
    @BusinessDataScope(menuPath = "business/train/trainCertificate/index")
    public List<TrainCertificate> selectTrainCertificateList(TrainCertificate trainCertificate)
    {
        List<TrainCertificate> TrainCertificatetList = trainCertificateMapper.selectTrainCertificateList(trainCertificate);
//        TrainCertificatetList.forEach(infotList -> {
//            //获取部门Id
//            Long workUnit = infotList.getDeptId();
//            R<SysDept> sysDept = remoteUserService.lists(workUnit);
//            if (sysDept.getData() != null) {
//                infotList.setDeptName(sysDept.getData().getDeptName());
//            }
//            //获取人员Id
//            String workUnit2 = infotList.getUserId();
//            Long deadline2 = Long.parseLong(workUnit2);
//            R<SysUser> sysUser = remoteUserService.getUserById(deadline2);
//            if (sysUser.getData() != null) {
//                infotList.setUserId(sysUser.getData().getUserName());
//            }
//        });
        return TrainCertificatetList;
    }

    /**
     * 新增人员证书
     *
     * @param trainCertificate 人员证书
     * @return 结果
     */
    @Override
    public int insertTrainCertificate(TrainCertificate trainCertificate)
    {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        trainCertificate.setTrainCertificateId(uuid);
        trainCertificate.setCreateTime(DateUtils.getNowDate());
        //根据证件类型自动生成证件复审日期
//        Date certificateGetDate = trainCertificate.getCertificateGetDate();
//        Calendar date = Calendar.getInstance();
//        date.setTime(certificateGetDate);
//        if(trainCertificate.getCertificateType().equals("1")){
//            date.add(Calendar.YEAR,3);
//        }else if(trainCertificate.getCertificateType().equals("2")){
//            date.add(Calendar.YEAR,6);
//        }else if(trainCertificate.getCertificateType().equals("3")){
//            date.add(Calendar.YEAR,3);
//        }
//        trainCertificate.setReviewDate(date.getTime());
        return trainCertificateMapper.insertTrainCertificate(trainCertificate);
    }

    /**
     * 新增人员证书文件信息
     *
     * @param trainCertificateList 人员证书文件信息
     * @return 结果
     */
    @Override
    public int addTrainCertificateFile(List<TrainCertificate> trainCertificateList) {
        int count = 0;
        for(TrainCertificate trainCertificate : trainCertificateList){
            //截取去后缀文件名

            String fileName = trainCertificate.getFileName();
            String fileNameStr = fileName.substring(0,fileName.lastIndexOf("."));
            // TODO  通过身份证正则匹配
//            //正则过滤文件名非法格式的文件
            String pattern = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x))-[\\u4e00-\\u9fa5]{0,}$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(fileNameStr);
            if(!m.matches()){
                continue;
            }
            //文件名拆分后获取文件匹配数据信息
            String[] parameters = fileNameStr.split("-");
            TrainCertificate updateTainCertificate = new TrainCertificate();
            //中文证件名转码
                switch(parameters[1]){
                    case "安全生产知识和管理能力考核合格证" :
                        updateTainCertificate.setCertificateType("1");
                        break;
                    case "煤矿特种作业人员操作证" :
                        updateTainCertificate.setCertificateType("2");
                        break;
                    case "通用行业特种作业人员操作证" :
                        updateTainCertificate.setCertificateType("3");
                        break;
                    case "特种设备操作证" :
                        updateTainCertificate.setCertificateType("4");
                        break;
                    case "煤矿企业其他从业人员安全培训合格证明" :
                        updateTainCertificate.setCertificateType("5");
                        break;
                    default :
                        updateTainCertificate.setCertificateType("unKnowType");
                }
                //未知文件名不参与文件信息更新
                if(updateTainCertificate.getCertificateType().equals("unKnowType")){
                    continue;
                }
            updateTainCertificate.setIdCardNum(parameters[0]);
            updateTainCertificate.setFileName(trainCertificate.getFileName());
            updateTainCertificate.setFileUrl(trainCertificate.getFileUrl());
            //根据文件名拆分后得到的有效信息匹配对应数据并将文件信息更新
            trainCertificateMapper.updateTrainCertificateFile(updateTainCertificate);
            count++;
        }
        return count;
    }

    /**
     * 修改人员证书
     *
     * @param trainCertificate 人员证书
     * @return 结果
     */
    @Override
    public int updateTrainCertificate(TrainCertificate trainCertificate)
    {
        trainCertificate.setUpdateTime(DateUtils.getNowDate());
        trainCertificate.setUpdateBy(SecurityUtils.getUsername());
        return trainCertificateMapper.updateTrainCertificate(trainCertificate);
    }

    /**
     * 批量删除人员证书
     *
     * @param trainCertificateIds 需要删除的人员证书主键
     * @return 结果
     */
    @Override
    public int deleteTrainCertificateByTrainCertificateIds(String[] trainCertificateIds)
    {
        return trainCertificateMapper.deleteTrainCertificateByTrainCertificateIds(trainCertificateIds);
    }

    /**
     * 删除人员证书信息
     *
     * @param trainCertificateId 人员证书主键
     * @return 结果
     */
    @Override
    public int deleteTrainCertificateByTrainCertificateId(String trainCertificateId)
    {
        return trainCertificateMapper.deleteTrainCertificateByTrainCertificateId(trainCertificateId);
    }

    @Override
    public String importData(List<TrainCertificate> dataManagementList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(dataManagementList) || dataManagementList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        dataManagementList.forEach(infotList -> {
        //获取人员信息
        String workUnit2 = infotList.getUserId();
        SysUser queryUser = new SysUser();
            queryUser.setUserName(workUnit2);
        R<SysUser> sysUser = remoteUserService.userInfo(queryUser);
        if (sysUser.getData() != null) {
            infotList.setUserId(Long.toString(sysUser.getData().getUserId()));
            infotList.setDeptId(sysUser.getData().getDeptId());
        }else {
            throw new ServiceException("用户"+workUnit2+"不存在！");
        }
        });
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<TrainCertificate> existList = selectTrainCertificateList(null);
        for (TrainCertificate importData : dataManagementList)
        {
            try {
                boolean Flag = false;
                for (TrainCertificate entry : existList) {
                    if (entry.getIdCardNum().equals(importData.getIdCardNum())&&entry.getCertificateType().equals(importData.getCertificateType())) {
                        Flag = true;
                        break;
                    }
                }
                if (!Flag) {
                    insertTrainCertificate(importData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + importData.getUserId() + " 导入成功");
                } else if (isUpdateSupport) {
                    updateTrainCertificate(importData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + importData.getUserId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、人员 " + importData.getUserId() +"的证书已存在");
                }
            }catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、人员： " + importData.getUserId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "数据已导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncTrainCertificate() {
        TrainCertificate certificate = new TrainCertificate();
        certificate.setSyncFlag(0);
        List<TrainCertificate> trainCertificates = trainCertificateMapper.selectTrainCertificateList(certificate);
        List<TrainCertificate> list = trainCertificates.stream().filter(item -> StringUtils.isNotEmpty(item.getIdCardNum())).collect(Collectors.toList());
        List<String> idNums = list.stream().map(TrainCertificate::getIdCardNum).collect(Collectors.toList());
        String[] array = new String[idNums.size()];
        array = idNums.toArray(array);
        JSONObject paramMap = new JSONObject();
        paramMap.put("tenantId", "00006");
        paramMap.put("idCards", array);
        String jsonStr = HttpUtil.post(trainingSystemUrl, paramMap.toJSONString(), 5000);
        JSONObject resultJson = JSONObject.parseObject(jsonStr);
        if (resultJson.getInteger("code") == 200) {
            List<TrainCertificate> data = JSON.parseArray(resultJson.getString("data"), TrainCertificate.class);
            list.stream().forEach(item -> {
                String idCardNum = item.getIdCardNum();
                List<TrainCertificate> certificates = data.stream().filter(s -> idCardNum.equals(s.getIdentityCard())).collect(Collectors.toList());
                if(certificates.size() > 0) {
                    //删除记录,以培训系统为准重新插入
                    this.deleteTrainCertificateByTrainCertificateId(item.getTrainCertificateId());
                    certificates.stream().forEach(cert -> {
                        cert.setSyncFlag(1);
                        cert.setIdCardNum(cert.getIdentityCard());
                        this.insertTrainCertificate(cert);
                    });
                }
            });
        }
    }

    @Override
    public int editBatch(String[] ids) {
        return trainCertificateMapper.editBatch(ids);
    }
}
